<script setup lang="ts">
import SInfo from '@/components/common/info/SInfo.vue'
import defaultAvatar from '@/assets/default-avatar.jpg'
import { addUserApi, updateUserApi, userInfoApi } from '@/api/user-api'
import type { ResultData } from '@/api/service'
import type { UserDto, UserVo } from '@/type/User'
import { useInfo } from '@/composables/info-composable'
import { onActivated, ref } from 'vue'
import { ElNotification } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useMenuStore } from '@/stores/menu'

const props = defineProps<{
  query: { userId?: string }
}>()

const router = useRouter()
const route = useRoute()
const menuStore = useMenuStore()

const lastUserId = ref<string | undefined>()

const { statement, infoLoading, infoData, isNew } = useInfo<UserVo>('UserInfo', getData)

onActivated(() => {
  if (lastUserId.value !== props.query.userId) {
    lastUserId.value = props.query.userId
    infoData.value = {
      avatar: '',
      createBy: '',
      email: '',
      gmtCreate: '',
      gmtModify: '',
      modifyBy: '',
      nickname: '',
      sign: '',
      status: 0,
      userId: '',
      username: ''
    }
    getData()
  }
})

function getData() {
  if (props.query.userId !== undefined) {
    infoLoading.value = true
    isNew.value = false
    // 页面传递userId, 调用接口查询数据回显
    userInfoApi(props.query.userId).then((response: ResultData<UserVo>) => {
      infoData.value = response.data
      infoLoading.value = false
    })
  }
}

const methods = {
  save: () => {
    const param: UserDto = {
      avatar: infoData.value.avatar,
      nickname: infoData.value.nickname,
      username: infoData.value.username,
      password: infoData.value.password,
      sign: infoData.value.sign,
      email: infoData.value.email,
      status: infoData.value.status
    }
    if (isNew.value) {
      // 新增
      addUserApi(param).then(() => {
        ElNotification.success({
          title: '成功',
          message: '新增用户',
          type: 'success'
        })
      })
    } else {
      // 修改用户信息
      updateUserApi(infoData.value.userId, param).then(() => {
        ElNotification.success({
          title: '成功',
          message: '更新用户',
          type: 'success'
        })
      })
    }
    // 执行返回方法
    methods.back()
  },
  back: () => {
    // 返回用户管理页面
    menuStore.closeTabOfPath(route.fullPath)
    router.push({ path: '/user' })
  }
}
</script>

<template>
  <s-info :data="infoData" :form-loading="infoLoading" :methods="methods" :statement="statement">
    <template #avatar="scope">
      <el-form-item :label="scope.mate.label">
        <el-avatar
          size="large"
          :src="scope.formItem.avatar === undefined ? defaultAvatar : scope.formItem.avatar"
        />
      </el-form-item>
    </template>
  </s-info>
</template>

<style scoped></style>
